﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Diagnostics;
using System.ComponentModel;
using ARR.UI.ViewModels;
using ARR.UI.Helpers;

namespace ARR.UI.Views
{
    public abstract class ViewBase : Window
    {
        private bool _checkDirty = false;

        public ViewBase()
        {            
            WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            
            Closing += new System.ComponentModel.CancelEventHandler(ViewBase_Closing);
            Closed += new System.EventHandler(ViewBase_Closed);
        }

        public bool CheckDirty
        {
            get { return _checkDirty; }
            set { _checkDirty = value; }
        }

        public void NotifyOwnerWindowClosing(object sender, CancelEventArgs e)
        {
            this.ClosingInternal(sender, e);
        }

        private void ViewBase_Closing(object sender, CancelEventArgs e)
        {
            this.ClosingInternal(sender, e);
        }

        private void ClosingInternal(object sender, CancelEventArgs e)
        {
            foreach (Window ownedWindow in this.OwnedWindows)
            {
                if (ownedWindow is ViewBase)
                    ((ViewBase)ownedWindow).NotifyOwnerWindowClosing(this, e);
            }

            if (e.Cancel)
                return;

            ViewModelBase viewModel = this.DataContext as ViewModelBase;

            if (viewModel != null)
            {
                if (_checkDirty && viewModel.IsDirty)
                {
                    
                }

                if (e.Cancel == false)
                {
                    viewModel.NotiftyOnClosing(sender, new EventArgs());
                }
            }
        }

        private void ViewBase_Closed(object sender, System.EventArgs e)
        {
            DataContext = null;
        }
    }

    
}
